package org.jeecg.modules.demo.crm.glm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.demo.crm.glm.util.ConvertRemoteFileToImageUtils;
import org.jeecg.modules.demo.crm.glm.util.HttpUtils;
import org.jeecg.modules.demo.crm.glm.util.JsonUtils;
import org.jeecg.modules.demo.crm.glm.util.PdfToImageUploader;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.util.List;

import static org.jeecg.modules.demo.crm.glm.util.JsonUtils.*;

@RestController
@RequestMapping("/glm4vflash")
public class GLM4VFlashController {


    @GetMapping("/ocr-assistant")
    @IgnoreAuth
    @ApiOperation(value="ocr识别", notes="ocr识别")
    public Result<JSONArray> ocrAssistant(@RequestParam(name="filePath",required=true) String filePath) throws Exception {
        // 构造请求数据
       String requestBody = JsonUtils.createRequestJsonImages(filePath,promptImages);
        // 发送请求到GLM-4V-Flash API
        String response = HttpUtils.sendPostRequest(MODEL_URL, API_KEY, requestBody);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if(jsonObject.get("choices") != null){
            JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
            String content = choices.getJSONObject("message").getString("content");
            String json = content.replaceAll("```json","").replaceAll("```","");
            JSONArray data = JSONArray.parseArray(json);
            System.out.println(content);
            return Result.OK(data);
        }
        // 返回结果
        return Result.error("识别失败");
    }

    @GetMapping("/invoice-parser")
    @IgnoreAuth
    @ApiOperation(value="发票ocr识别", notes="发票ocr识别")
    public Result<JSONArray> invoiceParser(@RequestParam(name="filePath",required=true) String filePath)
            throws Exception {
        try{
            if(filePath.toLowerCase().contains(".pdf") ){
                try {
                    filePath = PdfToImageUploader.convertPdfAndUploadImages(filePath, "temp");
                } catch (Exception e) {
                    System.err.println("无法转换 PDF 并上传图片: " + e.getMessage());
                    e.printStackTrace();
                }
            }

            String requestBody = JsonUtils.createRequestJsonImages(filePath,fapiaoprompt);
            String response = HttpUtils.sendPostRequest(MODEL_URL, API_KEY, requestBody);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if(jsonObject.get("choices") != null){
                JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
                String content = choices.getJSONObject("message").getString("content");
                String json = content.replaceAll("```json","")
                        .replaceAll("```","")
                        .replaceAll("¥","")
                        .replaceAll("¥","");
                JSONArray data = JSONArray.parseArray(json);
                if(data != null && data.size() > 0){
                    JSONObject infoJson = data.getJSONObject(0).getJSONObject("基础信息");
                    if(infoJson.get("备注") != null){
                        String remarks = infoJson.getString("备注");
                        String remarks2 =  remarks.replace("[","")
                                .replace("]","")
                                .replace("{","")
                                .replace("}","");
                        infoJson.put("备注",remarks2);
                        data.getJSONObject(0).put("基础信息",infoJson);
                    }
                }


                System.out.println(data);

                return Result.OK(data);
            }
//            System.out.println(data2);
//            JSONArray data = JSONArray.parseArray(data2);
//            return Result.OK(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
       return Result.error("识别失败");
    }

    @GetMapping("/additional-ocr")
    @IgnoreAuth
    @ApiOperation(value="需求ocr识别", notes="需求ocr识别")
    public Result<JSONArray> additionalOcr(@RequestParam(name="filePath",required=true) String filePath) throws Exception {
        try{
           /* String json2 = "[{\"项目名称\":\"临港仓库发货区安装固定插座\",\"维修/维保服务验收要求\":\"最大50M/个\",\"期望完成日期\":\"2025-06-20\",\"预计完成日期\":\"2025-06-20\",\"优先级\":\"紧急\",\"申请内容\":\"安装固定插座，更换插线板并固定。\",\"所属部门\":\"Operations\",\"预估费用(设备部填写)\":\"\",\"仓库\":\"临港仓库\",\"项目编号\":\"SCM2025061700775\",\"直接维修\":\"\",\"品牌、型号(采购适用)\":\"\",\"需求类型\":\"维修\",\"数量(采购适用)\":\"\",\"申请原因\":\"发货区各种线路复杂交错，拖线板未固定。使用多年未更换。\",\"标题\":\"设备维修申请-Ping Li-2025-06-17\",\"申请日期\":\"2025-06-17\",\"申请人\":\"Ping Li\"}]";
            JSONArray data2= JSONArray.parseArray(json2);
            return Result.OK(data2);*/

            String requestBody = JsonUtils.createRequestJsonImages(filePath,additional_prompt);
            String response = HttpUtils.sendPostRequest(MODEL_URL, API_KEY, requestBody);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if(jsonObject.get("choices") != null){
                JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
                String content = choices.getJSONObject("message").getString("content");
                String json = content.replaceAll("```json","").replaceAll("```","");
                JSONArray data = JSONArray.parseArray(json);
                System.out.println(data);
                return Result.OK(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.error("识别失败");
    }




    public static String data2 = "[{\"合计\":{\"税额\":\"￥34.51\",\"金额\":\"￥265.49\"},\"销售方信息\":{\"名称\":\"宁德市宁运油气销售有限公司\",\"统一社会信用代码/纳税人识别号\":\"91350902MA2Y2RTY97\"},\"购买方信息\":{\"名称\":\"普汇聚合(上海)储能有限公司\",\"统一社会信用代码/纳税人识别号\":\"91310116MAD9WAHJ4J\"},\"基础信息\":{\"项目名称\":\"*汽油*95#汽油\",\"税额\":\"￥34.51\",\"开票日期\":\"2025年03月15日\",\"开票人\":\"龚春艳\",\"发票类型\":\"电子发票(普通发票)\",\"价税合计（小写）\":\"300.00\",\"税率/征收率\":\"13%\",\"价税合计（大写）\":\"叁佰圆整\",\"备注\":\"\",\"发票号码\":\"25352000000028470074\",\"金额\":\"￥265.49\"}}]\n";



    public static String data = "```json\n" +
            "[\n" +
            "    {\n" +
            "        \"序号\": 1,\n" +
            "        \"名称\": \"镀锌铁皮风箱改造、保温\",\n" +
            "        \"数量\": 1,\n" +
            "        \"单位\": \"个\",\n" +
            "        \"主材\": 2800.00,\n" +
            "        \"辅材\": 500.00,\n" +
            "        \"人工\": 3500.00,\n" +
            "        \"总计\": 6800.00,\n" +
            "        \"备注\": \"\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 2,\n" +
            "        \"名称\": \"圆形纤维织物风管\",\n" +
            "        \"数量\": 25,\n" +
            "        \"单位\": \"M\",\n" +
            "        \"主材\": 1495.00,\n" +
            "        \"辅材\": 30.00,\n" +
            "        \"人工\": 80.00,\n" +
            "        \"总计\": 40125.00,\n" +
            "        \"备注\": \"1300mm\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 3,\n" +
            "        \"名称\": \"圆形纤维织物风管\",\n" +
            "        \"数量\": 76,\n" +
            "        \"单位\": \"M\",\n" +
            "        \"主材\": 560.00,\n" +
            "        \"辅材\": 20.00,\n" +
            "        \"人工\": 40.00,\n" +
            "        \"总计\": 47120.00,\n" +
            "        \"备注\": \"700mm\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 4,\n" +
            "        \"名称\": \"圆形纤维织物风管\",\n" +
            "        \"数量\": 33,\n" +
            "        \"单位\": \"M\",\n" +
            "        \"主材\": 480.00,\n" +
            "        \"辅材\": 20.00,\n" +
            "        \"人工\": 40.00,\n" +
            "        \"总计\": 17820.00,\n" +
            "        \"备注\": \"600mm\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 5,\n" +
            "        \"名称\": \"1300MM风管接头、变径\",\n" +
            "        \"数量\": 5,\n" +
            "        \"单位\": \"个\",\n" +
            "        \"主材\": 445.00,\n" +
            "        \"辅材\": 20.00,\n" +
            "        \"人工\": 100.00,\n" +
            "        \"总计\": 2825.00,\n" +
            "        \"备注\": \"1300mm接口\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 6,\n" +
            "        \"名称\": \"600mm风管接头\",\n" +
            "        \"数量\": 6,\n" +
            "        \"单位\": \"个\",\n" +
            "        \"主材\": 375.00,\n" +
            "        \"辅材\": 20.00,\n" +
            "        \"人工\": 100.00,\n" +
            "        \"总计\": 2970.00,\n" +
            "        \"备注\": \"600mm堵头\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 7,\n" +
            "        \"名称\": \"布袋风管调节阀\",\n" +
            "        \"数量\": 9,\n" +
            "        \"单位\": \"个\",\n" +
            "        \"主材\": 335.00,\n" +
            "        \"辅材\": 20.00,\n" +
            "        \"人工\": 100.00,\n" +
            "        \"总计\": 4095.00,\n" +
            "        \"备注\": \"700mm\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 8,\n" +
            "        \"名称\": \"吊架\",\n" +
            "        \"数量\": 134,\n" +
            "        \"单位\": \"M\",\n" +
            "        \"主材\": 175.00,\n" +
            "        \"辅材\": 40.00,\n" +
            "        \"人工\": 60.00,\n" +
            "        \"总计\": 36850.00,\n" +
            "        \"备注\": \"\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 9,\n" +
            "        \"名称\": \"升降车\",\n" +
            "        \"数量\": 1,\n" +
            "        \"单位\": \"M\",\n" +
            "        \"主材\": 5000.00,\n" +
            "        \"辅材\": 0.00,\n" +
            "        \"人工\": 0.00,\n" +
            "        \"总计\": 5000.00,\n" +
            "        \"备注\": \"\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"序号\": 10,\n" +
            "        \"名称\": \"旧管道拆除费用\",\n" +
            "        \"数量\": 1,\n" +
            "        \"单位\": \"项\",\n" +
            "        \"主材\": 0.00,\n" +
            "        \"辅材\": 500.00,\n" +
            "        \"人工\": 5000.00,\n" +
            "        \"总计\": 5500.00,\n" +
            "        \"备注\": \"\"\n" +
            "    }\n" +
            "]\n" +
            "```\n";


    @GetMapping("/quote-ocr")
    @IgnoreAuth
    @ApiOperation(value="报价ocr识别", notes="报价ocr识别")
    public Result<JSONArray> quoteOcr(@RequestParam(name="filePath",required=true) String filePath) throws Exception {
        try{
            List<BufferedImage> imgs = ConvertRemoteFileToImageUtils
                    .convert(filePath);
            String url = ConvertRemoteFileToImageUtils.toPngBytes(imgs.get(0));
            String requestBody = JsonUtils.createRequestJsonImages(url,quote_ocr_prompt);
            String response = HttpUtils.sendPostRequest(MODEL_URL, API_KEY, requestBody);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if(jsonObject.get("choices") != null){
                JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
                String content = choices.getJSONObject("message").getString("content");
                String json = content.replaceAll("```json","").replaceAll("```","");
                JSONArray data = JSONArray.parseArray(json);
                System.out.println(data);
                return Result.OK(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.error("识别失败");
    }
}

